package cn.kai.process.flow.node;

import cn.kai.process.flow.core.Node;
import cn.kai.process.flow.core.NodeContext;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 重试节点
 Author: cKnight
 Date: 2025/1/23
 */
@Slf4j
public class RetryNode implements Node {
    private Node node;
    /** 最大重试次数 */
    private Integer maxRetries;

    public RetryNode(Node node,Integer maxRetries){
        this.node = node;
        this.maxRetries = Objects.isNull(maxRetries) || maxRetries.equals(0) ? 5 : maxRetries;
    }

    @Override
    public void execute(NodeContext context) {
        Integer count = 0;
        while (count < maxRetries){
            try {
                node.exe(context);
                break;
            }catch (Exception e){
                count++;
                log.error("节点执行失败，开始第{}次重试",count);
                if (count.equals(maxRetries)){
                    log.error("节点执行失败，重试次数达到最大:{}，异常:",maxRetries,e);
                    throw e;
                }
            }
        }
    }
}
